package rbac

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"strings"
)

type Input struct {
	Method    string            `json:"method"`
	User      string            `json:"user"`
	Labels    map[string]string `json:"label"`
	ClusterId string            `json:"cluster_id"`
}

type RbacResponse struct {
	Code int `json:"code"`
	Data []struct {
		Expressions []struct {
			Value    bool   `json:"value"`
			Text     string `json:"text"`
			Location struct {
				Row int `json:"row"`
				Col int `json:"col"`
			} `json:"location"`
		} `json:"expressions"`
		Bindings struct {
			Allow bool `json:"allow"`
		} `json:"bindings"`
	} `json:"data"`
	Smg string `json:"smg"`
}

func GetOpa(url string, input Input) (error, *RbacResponse) {
	method := "POST"
	dataType, _ := json.Marshal(input)
	dataString := string(dataType)
	payload := strings.NewReader(dataString)
	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)
	if err != nil {
		return err, nil
	}
	req.Header.Add("Content-Type", "application/json")
	res, err := client.Do(req)
	if err != nil {
		return err, nil
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return err, nil
	}
	response := RbacResponse{}
	err = json.Unmarshal([]byte(string(body)), &response)
	if err != nil {
		return err, nil
	}
	return nil, &response
}
